import { useEffect } from 'react'
import { create } from 'zustand'

import { apiGetDynamicFieldList } from './apis'

/** 字典配置列表项 */
interface IDictionaryListItem {
  /** ID（唯一标识） */
  id: number
  /** 父ID，0表示根 */
  fid: number
  /** 名 */
  attrKey: string
  /** 值 */
  attrValue: string
  /** 排序 */
  orderNum: number
  childrenList?: IDictionaryListItem[]
}

interface IStore {
  dynamicFieldFetching: boolean
  dynamicFieldList: IDictionaryListItem[] | null
  getDynamicFieldList: () => void
}

const useBoundStore = create<IStore>((set, get) => {
  return {
    dynamicFieldFetching: false,
    dynamicFieldList: null,
    getDynamicFieldList: () => {
      const { dynamicFieldFetching, dynamicFieldList } = get()
      if (dynamicFieldFetching || dynamicFieldList) return
      set({ dynamicFieldFetching: true })
      apiGetDynamicFieldList(['dynamic_field', 'address', 'date'])
        .then(res => {
          set({ dynamicFieldFetching: false, dynamicFieldList: res })
        })
        .catch(err => {
          set({ dynamicFieldFetching: false })
          throw err
        })
    },
  }
})

/** 动态字段 */
const useDynamicField = () => {
  const dynamicFieldFetching = useBoundStore(v => v.dynamicFieldFetching)
  const dynamicFieldList = useBoundStore(v => v.dynamicFieldList)
  const getDynamicFieldList = useBoundStore(v => v.getDynamicFieldList)

  useEffect(() => getDynamicFieldList(), [getDynamicFieldList])

  return {
    /** 动态字段获取中 */
    dynamicFieldFetching,
    /** 动态字段列表 */
    dynamicFieldList,
  }
}

export type { IDictionaryListItem }
export { useDynamicField }
